package com.metamech.jabber.xml;

import java.util.HashMap;
import java.util.Iterator;

import org.apache.log4j.Logger;

public class QueueThread extends Thread {
	private static Logger logger=Logger.getLogger(QueueThread.class);
	PacketQueue packetQueue;
	HashMap packetListeners = new HashMap();
	
	public QueueThread(PacketQueue queue) { 
		packetQueue = queue;  
	}

	public boolean addListener(PacketListener listener, String element){
		if (listener == null || element == null){
			return false;
		}
		packetListeners.put(listener,element);
		return true;
	}

	public boolean removeListener(PacketListener listener){
		packetListeners.remove(listener);
		return true;
	}

	public void run(){
		logger.info("Queue Thread is Running");
		for( Packet packet = packetQueue.pull();
         	packet != null;
         	packet = packetQueue.pull()) {

			try {
				Packet child;
				String matchString;
				if (packet.getElement().equals("iq")){
					child = packet.getFirstChild("query");
					if (child == null){
						matchString = "iq";
					} else {
						matchString = child.getNamespace();
					}
				} else {
					matchString = packet.getElement();
				}

				synchronized(packetListeners){
					Iterator iter = packetListeners.keySet().iterator();
					while (iter.hasNext()){
						PacketListener listener = (PacketListener)iter.next();
						String listenerString = (String)packetListeners.get(listener);
						if (listenerString.equals(matchString)){
							listener.notify(packet);
						} // if
					} // while
				} // sync
			} catch (Exception ex){
				logger.error("QueueThread: ", ex); // Soldier on - no matter what
			}
		} // for
	} // run()
} // class QueueThread
